#include <func.h>
#include "blockq.h"

typedef struct {
	pthread_t* threads;
	int num;
	BlockQ* q;
} ThreadPool;

void* start_routine(void* arg){
	ThreadPool* pool = (ThreadPool*)arg;

	pthread_t tid = pthread_self();
	while(1){
		int task_id = blockq_pop(pool->q);
		printf("%ld execute task %d\n",tid,task_id);
		sleep(3);
		printf("%ld done task %d\n",tid,task_id);
	}
	return NULL;
}
ThreadPool* threadpool_create(int n){
	ThreadPool* pool = (ThreadPool*)malloc(sizeof(ThreadPool));

	pool->threads= (pthread_t*)malloc(sizeof(pthread_t)*n);
	pool->num = n;
	pool->q = blockq_create();

	for(int i=0;i<n;i++){
		pthread_create(pool->threads+i,NULL,start_routine,pool);
	}
	return pool;
}

void threadpool_destory(ThreadPool* pool){
	blockq_destroy(pool->q);
	free(pool->threads);
	free(pool);
}


int main()
{
	//创建线程池
	ThreadPool* pool = threadpool_create(8);

	//主线程逻辑
	for(int i = 1;i<=100;i++){
		blockq_push(pool->q,i);
	}

	//退出
	//有序退出 
	for(int i=0;i<pool->num;i++){
		pthread_join(pool->threads[i],NULL);
	}
	threadpool_destory(pool);
    return 0;
}

